package com.iflytek.aidemo.student;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;

import java.util.Calendar;

/**
 * 学生端-每周一定时设置“上周错题练习”待办标记。
 */
public class WrongPushScheduler {
    private static final int REQ_CODE_WEEKLY_PUSH = 10021;

    /**
     * 计划每周一9:00触发广播（近似），触发时仅设置一个SharedPreferences标志位。
     */
    public static void scheduleWeekly(Context context) {
        try {
            AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            if (am == null) return;

            Intent intent = new Intent(context, WrongPushReceiver.class);
            PendingIntent pi = PendingIntent.getBroadcast(
                    context,
                    REQ_CODE_WEEKLY_PUSH,
                    intent,
                    PendingIntent.FLAG_UPDATE_CURRENT | (Build.VERSION.SDK_INT >= 23 ? PendingIntent.FLAG_IMMUTABLE : 0)
            );

            // 计算下一个周一9:00
            Calendar cal = Calendar.getInstance();
            cal.set(Calendar.SECOND, 0);
            cal.set(Calendar.MILLISECOND, 0);
            cal.set(Calendar.MINUTE, 0);
            cal.set(Calendar.HOUR_OF_DAY, 9);
            // Calendar.MONDAY = 2
            while (cal.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY || cal.getTimeInMillis() <= System.currentTimeMillis()) {
                cal.add(Calendar.DAY_OF_MONTH, 1);
            }

            long triggerAt = cal.getTimeInMillis();
            long intervalWeek = 7L * 24 * 60 * 60 * 1000;

            // 使用inexact以降低功耗，系统会近似调度
            am.setInexactRepeating(AlarmManager.RTC_WAKEUP, triggerAt, intervalWeek, pi);
        } catch (Exception ignored) { }
    }
}
